import defaultMdxComponents from 'fumadocs-ui/mdx';
import type { MDXComponents } from 'mdx/types';
import { icons } from 'lucide-react';
import { createElement } from 'react';
import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';
import { Files, Folder, File } from 'fumadocs-ui/components/files';
import { Tabs, Tab } from 'fumadocs-ui/components/tabs';
import * as FcIcons from 'react-icons/fc';
import * as FaIcons from 'react-icons/fa';

// 合并所有图标
const allIcons = {
  ...icons,
  ...FcIcons,
  ...FaIcons
};

// 自定义文本组件
const CustomText = ({ children, className }: { children: React.ReactNode; className?: string }) => {
  const classes = className?.split(' ') || [];
  const styles: string[] = [];

  // 处理颜色
  if (classes.includes('text-red')) styles.push('text-red-500 [&_code]:text-red-500');
  if (classes.includes('text-blue')) styles.push('text-blue-500 [&_code]:text-blue-500');
  if (classes.includes('text-green')) styles.push('text-green-500 [&_code]:text-green-500');
  if (classes.includes('text-yellow')) styles.push('text-yellow-500 [&_code]:text-yellow-500');
  if (classes.includes('text-purple')) styles.push('text-purple-500 [&_code]:text-purple-500');
  if (classes.includes('text-pink')) styles.push('text-pink-500 [&_code]:text-pink-500');

  // 处理字重
  if (classes.includes('font-bold')) styles.push('font-bold [&_code]:font-bold');
  if (classes.includes('font-semibold')) styles.push('font-semibold [&_code]:font-semibold');

  // 处理下划线
  if (classes.includes('underline')) styles.push('underline [&_code]:underline');

  // 处理斜体
  if (classes.includes('italic')) styles.push('italic [&_code]:italic');

  return <span className={styles.join(' ')}>{children}</span>;
};

// use this function to get MDX components, you will need it for rendering MDX
export function getMDXComponents(components?: MDXComponents): MDXComponents {
  return {
    ...defaultMdxComponents,
    ...components,
    Accordion,
    Accordions,
    Files,
    Folder,
    File,
    Tabs,
    Tab,
    CustomText,
    Card: (props: any) => {
      const { icon, title, ...rest } = props;
      if (icon && icon in allIcons) {
        const IconComponent = allIcons[icon as keyof typeof allIcons];
        return defaultMdxComponents.Card({
          ...rest,
          title: (
            <div className="flex items-center gap-2">
              {createElement(IconComponent, { size: 16 })}
              <span>{title}</span>
            </div>
          ),
        });
      }
      return defaultMdxComponents.Card(props);
    },
  };
}
